﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HBKY.Shop.Common.Extension
{
    /// <summary>
    /// 计算扩展
    /// </summary>
    public static class NumericalExtension
    {
        /// <summary>
        /// 计算时光值
        /// </summary>
        public static double PercentRank(this List<double> matrix, double value)
        {
            if (!matrix.HasContent()) return 0;
            matrix.Sort();
            var pos = matrix.IndexOf(value) + 1;
            return Math.Round((pos * 1d / matrix.Count) * 100, 2);
        }

        /// <summary>
        /// 计算百分位
        /// </summary>
        /// <param name="seq"></param>
        /// <param name="percentile"></param>
        /// <returns></returns>
        public static double Percentile(this IEnumerable<double> seq, double percentile)
        {
            var elements = seq.ToArray();
            //Array.Sort(elements); //外部排序好内部不需要在此次排序

            var realIndex = percentile * (elements.Length - 1);
            var index = (int)realIndex;
            var frac = realIndex - index;

            if (index + 1 < elements.Length)
                return elements[index] * (1 - frac) + elements[index + 1] * frac;
            return elements[index];
        }


        /// <summary>
        /// 当前百分位
        /// </summary>
        public static string CurrentPercentile(this List<double> seq, double percentile)
        {
            var pos = seq.IndexOf(percentile) + 1;
            return ((pos * 1d - 1) / (seq.Count() - 1) * 100).ToString("0.00") + "%";
        }

        /// <summary>
        /// 百分之20 分位
        /// </summary>
        public static string PercentileQ2V(this IEnumerable<double> matrix)
        {
            return Math.Round(matrix.Percentile(0.2d), 2).ToString("0.00");
        }

        /// <summary>
        /// 百分之50 分位
        /// </summary>
        public static string PercentileQ5V(this IEnumerable<double> matrix)
        {
            return Math.Round(matrix.Percentile(0.5d), 2).ToString("0.00");
        }

        /// <summary>
        /// 百分之80 分位
        /// </summary>
        public static string PercentileQ8V(this IEnumerable<double> matrix)
        {
            return Math.Round(matrix.Percentile(0.8d), 2).ToString("0.00");
        }


        /// <summary>
        /// 保留两位
        /// </summary>
        public static string ToFixed2(this decimal value)
        {
            return value.ToString("0.00");
        }
        /// <summary>
        /// 保留两位
        /// </summary>
        public static string ToFixed2(this decimal? value)
        {
            if (value == default) return "--";
            return value.Value.ToString("0.00");
        }

        /// 保留两位
        /// </summary>
        public static string ToFixed2(this double value)
        {
            return value.ToString("0.00");
        }
    }
}
